package com.whosly.action.log.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

/**
 * IP获取工具, 除在/etc/hosts中显式配置外, 保证不获取到环回地址和ipv6地址等带冒号的地址
 */
@Slf4j
public class IpUtil {
    public static boolean machineIpEqual(String targetIp) {
        Enumeration<NetworkInterface> netInterfaces = null;
        try {
            netInterfaces = NetworkInterface.getNetworkInterfaces();
        } catch (SocketException e) {
            log.error("IpUtil SocketException:", e);
            return  false;
        }
        InetAddress ip = null;
        while (netInterfaces.hasMoreElements()) {
            NetworkInterface ni = netInterfaces.nextElement();
            Enumeration<InetAddress> address = ni.getInetAddresses();
            while (address.hasMoreElements()) {
                ip = address.nextElement();
                String ipStr = ip.getHostAddress();
                if(targetIp.equalsIgnoreCase(ipStr)){
                    return  true;
                }
            }
        };

        log.error("没有找到可执行机器：{}.", targetIp);
        return false;
    }

    public static String getRealIp() throws SocketException {
        String localIp = null;
        String netip = null;
        Enumeration<NetworkInterface> netInterfaces = NetworkInterface.getNetworkInterfaces();
        InetAddress ip = null;
        boolean finded = false;

        while(netInterfaces.hasMoreElements() && !finded) {
            NetworkInterface ni = (NetworkInterface)netInterfaces.nextElement();
            Enumeration address = ni.getInetAddresses();

            while(address.hasMoreElements()) {
                ip = (InetAddress)address.nextElement();
                if (!ip.isSiteLocalAddress() && !ip.isLoopbackAddress() && !ip.getHostAddress().equals("127.0.0.1") && ip.getHostAddress().indexOf(":") == -1) {
                    netip = ip.getHostAddress();
                    finded = true;
                    break;
                }

                if (ip.isSiteLocalAddress() && !ip.isLoopbackAddress() && !ip.getHostAddress().equals("127.0.0.1") && ip.getHostAddress().indexOf(":") == -1) {
                    localIp = ip.getHostAddress();
                }
            }
        }

        return !StringUtils.isEmpty(netip) ? netip : localIp;
    }


}
